import numpy
from sklearn import preprocessing


def label():

    # 创建LabelEncoder对象
    encoder = preprocessing.LabelEncoder()

    # 训练LabelEncoder，学习标签与编码的映射关系
    encoder.fit(["a","b", "d", "e",  "f"])

    # 将标签转换为编码
    encoded_labels = encoder.transform(["a", "d", "e", "f"])

    # 输出编码后的结果
    print(encoded_labels)  # 输出: [2, 1, 0]

    # 将编码转换回原始标签
    original_labels = encoder.inverse_transform(encoded_labels)
    print(original_labels)


def onehot():
    cities = ['北京', '上海', '广州']
    genders = ['男', '女', '男']

    # 建立OneHotEncoder对象
    encoder1 = preprocessing.OneHotEncoder(categories='auto', sparse=False)

    # 转换城市列变量
    cities_new = encoder1.fit_transform(numpy.array(cities).reshape([-1, 1]))

    # 打印转换后的结果
    print(cities_new)


label()
onehot()
